#include "StdAfx.h"
#include "DRendererSFML.h"
#include <SFML/Graphics.hpp>
#include "../DGlobals.h"
#include "DImage.h"
#include "DAnimation.h"
#include "../Actors/DIActor.h"
#include "../Actors/DBackground.h"

DRendererSFML::DRendererSFML(boost::shared_ptr<sf::RenderWindow> device)
: DIRenderer()
, m_device(device)
{
	
}

DRendererSFML::~DRendererSFML(void)
{
}

boost::shared_ptr<sf::RenderWindow> DRendererSFML::device() const
{
    return m_device.lock();
}

void DRendererSFML::render(boost::shared_ptr<DIActor> actor)
{
    sf::Sprite sprite;

	boost::shared_ptr<DAnimation> anim = actor->currentAnimation();
	boost::shared_ptr<DImageSFML> curFrame = boost::static_pointer_cast<DImageSFML>(anim->currentFrame());

    const DGraphicsParams params = actor->graphicsParams();
    vec2 pos = actor->pos();
    vec2 scale = actor->scale();

	sprite.SetPosition(pos.x, pos.y);
    sprite.Scale(scale.x, scale.y);

	sprite.SetImage(*(curFrame->sfmlImage()));
    sprite.SetColor(sf::Color(params.redChannel(), params.greenChannel(),
        params.blueChannel(), params.alphaChannel()));
    sprite.FlipX(params.isFlippedX());
    sprite.FlipY(params.isFlippedY());

	m_device.lock()->Draw(sprite);
}

void DRendererSFML::render(const std::list<boost::shared_ptr<DIActor> >& actors)
{
	foreach(boost::shared_ptr<DIActor> actor, actors)
	{
		render(actor);
	}
}

void DRendererSFML::render(boost::shared_ptr<DBackground> back)
{
	vec2 pos = back->pos();
	sf::Sprite sprite;
	boost::shared_ptr<DAnimation> anim = back->animation();
	boost::shared_ptr<DImageSFML> curFrame = boost::static_pointer_cast<DImageSFML>(anim->currentFrame());

	sprite.SetPosition(pos.x, pos.y);
	sprite.SetImage(*(curFrame->sfmlImage()));

	m_device.lock()->Draw(sprite);

    if(back->isScrolling())
    {
        float secondTilePos = pos.x + (float)anim->width();
	    sprite.SetPosition(secondTilePos, pos.y);
        m_device.lock()->Draw(sprite);
    }

}